//
//  SIXHomeController.m
//  weibo
//
//  Created by chenangel on 16/5/20.
//  Copyright © 2016年 chuhan. All rights reserved.
//

#import "SIXHomeController.h"
#import "SIXAccountTool.h"
#import "SIXAccount.h"
#import "SIXApiTestController.h"
#import "AFNetworking.h"
#import <MJRefresh.h>
#import "UIBarButtonItem+Extension.h"


#import "SIXAccountTool.h"
//下拉菜单
#import "SIXTitleBtn.h"
#import "SIXMenuDrownView.h"
#import "SIXTitleMenuViewController.h"

//cell相关
#import "SIXStatusCell.h"
#import "SIXStatus.h"
#import "SIXStatusFrame.h"
#import "SIXUser.h"


@interface SIXHomeController ()<SIXMenuDrownViewDelegate>
/**
 *  微博数组（里面放的都是SIXStatusFrame模型，一个SIXStatusFrame对象就代表一条微博）
 */
@property (nonatomic, strong) NSMutableArray *statusFrames;

@end

@implementation SIXHomeController


- (NSMutableArray *)statusFrames
{
    if (!_statusFrames) {
        self.statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    [self testapi];

    self.tableView.backgroundColor = SIXColor(211, 211, 211);

    // 1.1设置导航栏内容
    [self setupNav];
    
    // 1.2获得用户信息（昵称）
    [self setupUserInfo];
    
    
    // 1.3设置上下拉刷新控件
    [self setupRefresh];
    
    [SIXNoteCenter addObserver:self selector:@selector(loadNewStatus) name:SIXTabBarDidSelectNotification object:nil];
    
}
#pragma mark -- 初始化配置系列方法
- (void)setupNav{
    /* 设置导航栏上面的内容 */
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(friendSearch) image:@"navigationbar_friendsearch" heighlightImage:@"navigationbar_friendsearch_highlighted"];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(pop) image:@"navigationbar_pop" heighlightImage:@"navigationbar_pop_highlighted"];
    
    /* 中间的标题按钮 */
    SIXTitleBtn *titleButton = [[SIXTitleBtn alloc] init];
    // 设置图片和文字
    NSString *name = [SIXAccountTool account].name;
    NSLog(@"name---%@",name);
    if (name.length >0) {
        
        [titleButton setTitle:(name?name:@"首页") forState:UIControlStateNormal];

    }
    
    // 监听标题点击
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
}
//获取用户信息
- (void)setupUserInfo{
    // 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.拼接请求参数
    SIXAccount *account = [SIXAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = account.uid;
    
    // 3.发送请求
    [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        // 标题按钮
        UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
        // 设置名字
        SIXUser *user = [SIXUser mj_objectWithKeyValues:responseObject];
        [titleButton setTitle:user.name forState:UIControlStateNormal];
        
        // 存储昵称到沙盒中
        account.name = user.name;
        [SIXAccountTool saveAccount:account];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        SIXLog(@"请求失败-%@", error);
    }];
}
- (void)setupRefresh{


    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewStatus];
    }];
    
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreStatus)];
}

#pragma mark -- 上下拉刷新触发方法
/**
 *  显示最新微博的数量
 *
 *  @param count 最新微博的数量
 */
- (void)showNewStatusCount:(NSUInteger)count
{
    // 刷新成功(清空图标数字)
    self.tabBarItem.badgeValue = nil;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    // 1.创建label
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.width = [UIScreen mainScreen].bounds.size.width;
    label.height = 35;
    
    // 2.设置其他属性
    if (count == 0) {
        label.text = @"没有新的微博数据，稍后再试";
    } else {
        label.text = [NSString stringWithFormat:@"共有%zd条新的微博", count];
    }
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16];
    
    // 3.添加
    label.y = 64 - label.height;
    // 将label添加到导航控制器的view中，并且是盖在导航栏下边
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    // 4.动画
    // 先利用1s的时间，让label往下移动一段距离
    CGFloat duration = 1.0; // 动画的时间
    [UIView animateWithDuration:duration animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        // 延迟1s后，再利用1s的时间，让label往上移动一段距离（回到一开始的状态）
        CGFloat delay = 1.0; // 延迟1s
        // UIViewAnimationOptionCurveLinear:匀速
        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
    
}


//刷新最新
- (void)loadNewStatus{
    SIXLog(@"上啦刷新");
    // 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.拼接请求参数
    SIXAccount *account = [SIXAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    
    // 取出最前面的微博（最新的微博，ID最大的微博）
    SIXStatusFrame *firstStatusF = [self.statusFrames firstObject];
    if (firstStatusF) {
        // 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
        params[@"since_id"] = firstStatusF.status.idstr;
    }
    
    // 3.发送请求
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        [self.tableView.mj_header endRefreshing];
        SIXLog(@"%@", responseObject);
        
        // 将 "微博字典"数组 转为 "微博模型"数组
        NSArray *newStatuses = [SIXStatus mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        // 将 Status数组 转为 StatusFrame数组
        NSArray *newFrames = [self stausFramesWithStatuses:newStatuses];
        
        // 将最新的微博数据，添加到总数组的最前面
        NSRange range = NSMakeRange(0, newFrames.count);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statusFrames insertObjects:newFrames atIndexes:set];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 结束刷新
//        [self.tableView.mj_header endRefreshing];
        
        // 显示最新微博的数量
        [self showNewStatusCount:newStatuses.count];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        SIXLog(@"请求失败-%@", error);
    }];
}
//加载更多
- (void)loadMoreStatus{
    // 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.拼接请求参数
    SIXAccount *account = [SIXAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    
    // 取出最后面的微博（最新的微博，ID最大的微博）
    SIXStatusFrame *lastStatusF = [self.statusFrames lastObject];
    if (lastStatusF) {
        // 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        // id这种数据一般都是比较大的，一般转成整数的话，最好是long long类型
        long long maxId = lastStatusF.status.idstr.longLongValue - 1;
        params[@"max_id"] = @(maxId);
    }
    
    // 3.发送请求
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        // 将 "微博字典"数组 转为 "微博模型"数组
        NSArray *newStatuses = [SIXStatus mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        // 将 Status数组 转为 StatusFrame数组
        NSArray *newFrames = [self stausFramesWithStatuses:newStatuses];
        
        // 将更多的微博数据，添加到总数组的最后面
        [self.statusFrames addObjectsFromArray:newFrames];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 结束刷新(隐藏footer)
        self.tableView.tableFooterView.hidden = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        SIXLog(@"请求失败-%@", error);
        
        // 结束刷新
        self.tableView.tableFooterView.hidden = YES;
    }];
}

/**
 *  将Status模型转为StatusFrame模型
 */
- (NSArray *)stausFramesWithStatuses:(NSArray *)statuses
{
    NSMutableArray *frames = [NSMutableArray array];
    for (SIXStatus *status in statuses) {
        SIXStatusFrame *f = [[SIXStatusFrame alloc] init];
        f.status = status;
        [frames addObject:f];
    }
    return frames;
}

#pragma mark -- 导航按钮
//左边搜索
- (void)friendSearch{
    NSLog(@"friendSearch");
}
//右边弹出
- (void)pop{
    NSLog(@"pop");
    
}

//顶部标题点击弹出
- (void)titleClick:(UIButton*)titleButton{
    // 1.创建下拉菜单视图
    SIXMenuDrownView *menu = [SIXMenuDrownView menu];
    menu.delegate = self;
    
    // 2.设置内容下拉菜单视图的内容（内容是一个tableView表格）
    SIXTitleMenuViewController *vc = [[SIXTitleMenuViewController alloc] init];
    vc.view.height = 150;
    vc.view.width = 150;
    menu.contentController = vc;
    // 3.显示
    [menu showFrom:titleButton];
}
#pragma mark - SIXDropdownMenuDelegate
/**
 *  下拉菜单被销毁了
 */
- (void)dropdownMenuDidDismiss:(SIXMenuDrownView *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    // 让箭头向下
    titleButton.selected = NO;
}

/**
 *  下拉菜单显示了
 */
- (void)dropdownMenuDidShow:(SIXMenuDrownView *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    // 让箭头向上
    titleButton.selected = YES;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statusFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 获得cell
    SIXStatusCell *cell = [SIXStatusCell cellWithTableView:tableView];
    
    // 给cell传递模型数据
    cell.statusFrame = self.statusFrames[indexPath.row];
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    // 如果tableView还没有数据，就直接返回
    if (self.statusFrames.count == 0 || self.tableView.tableFooterView.isHidden == NO) return;
    
    CGFloat offsetY = scrollView.contentOffset.y;
    // 当最后一个cell完全显示在眼前时，contentOffset的y值
    CGFloat judgeOffsetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height - self.tableView.tableFooterView.height;
    if (offsetY >= judgeOffsetY) {
        [self.tableView.mj_header endRefreshing];
        // 最后一个cell完全进入视野范围内
        // 显示footer
        //self.tableView.mj_footer.hidden = NO;
        //[self.tableView.mj_footer beginRefreshing];
        // 加载更多的微博数据
        //[self loadMoreStatus];
    }
    self.tableView.mj_footer.hidden = NO;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SIXStatusFrame *frame = self.statusFrames[indexPath.row];
    return frame.cellHeight;
}

#pragma mark -- 测试方法
- (void)saveData{
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json?access_token=2.00khaCOGTp5MdD67ff0bacddLzrtuC&page=1" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"%@---%@",[responseObject class],responseObject[@"statuses"]);
        NSArray *arr = responseObject[@"statuses"];
        [arr writeToFile:@"/Users/chenangel/Desktop/未命名文件夹/a.plist" atomically:YES];

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}
- (void)testapi{
    self.view.backgroundColor = [UIColor redColor];
    UIButton *apibtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [apibtn setTitle:@"api测试按钮" forState:UIControlStateNormal];
    [apibtn setTitle:@"api测试按钮" forState:UIControlStateSelected];
    
    apibtn.frame = CGRectMake(150, 250, 120, 50);
    
    [apibtn addTarget:self action:@selector(apiTestVC) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:apibtn];

}
- (void)apiTestVC{
    SIXApiTestController *apiVC = [[SIXApiTestController alloc]init];
    apiVC.view.backgroundColor = [UIColor orangeColor];
    
    SIXAccount *acount = [SIXAccountTool account];
    NSLog(@"access_token-----%@-------%@",acount.access_token,acount.uid);
    
    [self.navigationController pushViewController:apiVC animated:YES];
    [self saveData];
}



@end
